﻿using AsscerMVCN2512.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace AssetManagementSystem.Controllers
{
    public class AssetPutController : Controller
    {
        private AssetDBEntities1 db = new AssetDBEntities1();

        // GET: 主页面
        public ActionResult Index()
        {
            return View();
        }

        // GET: 获取资产入库列表
        [HttpGet]
        public JsonResult GetAssetPutList(int page = 1, int limit = 10, string AssetName = "", string EmpolyName = "", string AssetType = "")
        {
            try
            {
                // 基础查询
                var query = from ap in db.AssetPutInfo
                            join a in db.AssetInfo on ap.AssetID equals a.AssetID
                            join e in db.EmpolyInfo on ap.EmpolyID equals e.EmpolyID
                            join at in db.AssetTypeInfo on a.AssetTypeID equals at.AssetTypeID
                            select new
                            {
                                ap.AssetPutID,
                                ap.AssetID,
                                AssetName = a.AssetName,
                                AssetTypeID = a.AssetTypeID,
                                AssetTypeName = at.AssetTypeName,
                                ap.AssetPutCount,
                                ap.AssetPutDate,
                                ap.EmpolyID,
                                EmpolyName = e.EmpolyName,
                                ap.AssetPutReMark
                            };

                // 应用筛选条件
                if (!string.IsNullOrEmpty(AssetName))
                {
                    query = query.Where(x => x.AssetName.Contains(AssetName));
                }

                if (!string.IsNullOrEmpty(EmpolyName))
                {
                    query = query.Where(x => x.EmpolyName.Contains(EmpolyName));
                }

                if (!string.IsNullOrEmpty(AssetType))
                {
                    int assetTypeId = int.Parse(AssetType);
                    query = query.Where(x => x.AssetTypeID == assetTypeId);
                }

                // 获取总数
                var total = query.Count();

                // 分页数据
                var data = query.OrderByDescending(x => x.AssetPutDate)
                              .Skip((page - 1) * limit)
                              .Take(limit)
                              .ToList();

                return Json(new
                {
                    Code = 200,
                    Message = "获取成功",
                    Data = new { Total = total, Items = data }
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    Code = 500,
                    Message = "获取失败：" + ex.Message,
                    Data = new { Total = 0, Items = new List<object>() }
                }, JsonRequestBehavior.AllowGet);
            }
        }

        // GET: 根据ID获取入库记录
        [HttpGet]
        public JsonResult GetAssetPutById(int id)
        {
            try
            {
                var assetPut = db.AssetPutInfo.Find(id);
                if (assetPut == null)
                {
                    return Json(new { Code = 404, Message = "记录不存在" }, JsonRequestBehavior.AllowGet);
                }

                return Json(new { Code = 200, Message = "获取成功", Data = assetPut }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { Code = 500, Message = "获取失败：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        // POST: 新增资产入库
        [HttpPost]
        public JsonResult AddAssetPut(AssetPutInfo model)
        {
            using (var transaction = db.Database.BeginTransaction())
            {
                try
                {
                    // 验证数据
                    if (model.AssetID <= 0)
                    {
                        return Json(new { Code = 400, Message = "请选择资产" });
                    }

                    if (model.EmpolyID <= 0)
                    {
                        return Json(new { Code = 400, Message = "请选择入库人员" });
                    }

                    if (model.AssetPutCount <= 0)
                    {
                        return Json(new { Code = 400, Message = "入库数量必须大于0" });
                    }

                    // 设置默认值
                    if (model.AssetPutDate == null || model.AssetPutDate == DateTime.MinValue)
                    {
                        model.AssetPutDate = DateTime.Now;
                    }

                    // 验证资产是否存在
                    var asset = db.AssetInfo.Find(model.AssetID);
                    if (asset == null)
                    {
                        return Json(new { Code = 400, Message = "选择的资产不存在" });
                    }

                    // 验证员工是否存在
                    var empoly = db.EmpolyInfo.Find(model.EmpolyID);
                    if (empoly == null)
                    {
                        return Json(new { Code = 400, Message = "选择的员工不存在" });
                    }

                    // 创建新的入库记录对象
                    var assetPut = new AssetPutInfo
                    {
                        AssetID = model.AssetID,
                        AssetPutCount = model.AssetPutCount,
                        EmpolyID = model.EmpolyID,
                        AssetPutDate = model.AssetPutDate,
                        AssetPutReMark = model.AssetPutReMark
                    };

                    // 保存入库记录
                    db.AssetPutInfo.Add(assetPut);
                    db.SaveChanges(); // 先保存入库记录

                    // 自动添加明细资产数据
                    for (int i = 0; i < model.AssetPutCount; i++)
                    {
                        var assetDetail = new AssetDetailInfo
                        {
                            AssetID = model.AssetID,
                            AssetDetailNum = GenerateAssetDetailNum(asset.AssetName, i + 1),
                            AssetDetailUseState = 1, // 1: 未使用
                            AssetDetailUseDate = DateTime.Now,
                            AssetDetailServiceState = 0, // 0: 正常
                            AssetDetailDumState = 0, // 0: 正常
                            EmpolyID = null, // 改为null，避免外键约束问题
                            AreaID = null, // 改为null，避免外键约束问题
                            AssetAreaReMark = "自动生成的明细资产"
                        };
                        db.AssetDetailInfo.Add(assetDetail);
                    }

                    db.SaveChanges(); // 保存明细记录
                    transaction.Commit();

                    return Json(new { Code = 200, Message = "入库成功，并自动生成" + model.AssetPutCount + "条明细资产记录" });
                }
                catch (System.Data.Entity.Infrastructure.DbUpdateException dbEx)
                {
                    transaction.Rollback();
                    // 获取内部异常信息
                    var innerException = dbEx.InnerException?.InnerException ?? dbEx.InnerException ?? dbEx;
                    string errorMessage = "数据库更新失败: " + innerException.Message;

                    // 如果是外键约束错误，给出更友好的提示
                    if (innerException.Message.Contains("foreign key") || innerException.Message.Contains("约束"))
                    {
                        errorMessage = "数据关联错误，请检查选择的资产或员工是否存在";
                    }

                    return Json(new { Code = 500, Message = errorMessage });
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException ex)
                {
                    transaction.Rollback();
                    var errorMessages = ex.EntityValidationErrors
                        .SelectMany(x => x.ValidationErrors)
                        .Select(x => $"{x.PropertyName}: {x.ErrorMessage}");
                    var fullErrorMessage = string.Join("; ", errorMessages);
                    return Json(new { Code = 500, Message = "数据验证失败: " + fullErrorMessage });
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    // 获取最内部的异常信息
                    var innerException = ex.InnerException ?? ex;
                    return Json(new { Code = 500, Message = "入库失败：" + innerException.Message });
                }
            }
        }

        // POST: 修改资产入库
        [HttpPost]
        public JsonResult UpdateAssetPut(AssetPutInfo model)
        {
            try
            {
                var assetPut = db.AssetPutInfo.Find(model.AssetPutID);
                if (assetPut == null)
                {
                    return Json(new { Code = 404, Message = "记录不存在" });
                }

                // 验证数据 - 只验证可修改的字段
                if (model.AssetPutCount <= 0)
                {
                    return Json(new { Code = 400, Message = "入库数量必须大于0" });
                }

                // 只能修改入库数量、入库时间、备注
                assetPut.AssetPutCount = model.AssetPutCount;
                assetPut.AssetPutDate = model.AssetPutDate;
                assetPut.AssetPutReMark = model.AssetPutReMark;

                int result = db.SaveChanges();

                if (result > 0)
                {
                    return Json(new { Code = 200, Message = "修改成功" });
                }
                else
                {
                    return Json(new { Code = 500, Message = "修改失败" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { Code = 500, Message = "修改失败：" + ex.Message });
            }
        }

        // GET: 获取资产列表（用于下拉框）
        [HttpGet]
        public JsonResult GetAssets()
        {
            try
            {
                var assets = db.AssetInfo
                    .Select(a => new
                    {
                        a.AssetID,
                        a.AssetName
                    })
                    .OrderBy(a => a.AssetName)
                    .ToList();

                return Json(new { Code = 200, Message = "获取成功", Data = assets }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { Code = 500, Message = "获取失败：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        // GET: 获取员工列表（用于下拉框）
        [HttpGet]
        public JsonResult GetEmpolys()
        {
            try
            {
                var empolys = db.EmpolyInfo
                    .Where(e => e.DepartureDate == null) // 只显示在职员工
                    .Select(e => new
                    {
                        e.EmpolyID,
                        e.EmpolyName
                    })
                    .OrderBy(e => e.EmpolyName)
                    .ToList();

                return Json(new { Code = 200, Message = "获取成功", Data = empolys }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { Code = 500, Message = "获取失败：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        // 生成资产明细编号
        // 生成资产明细编号 - 限制在10个字符以内
        private string GenerateAssetDetailNum(string assetName, int index)
        {
            string prefix = "";

            // 从资产名称中提取字母，最多取3个字符
            foreach (char c in assetName)
            {
                if (char.IsLetter(c))
                {
                    prefix += c;
                    if (prefix.Length >= 3) break; // 最多取3个字母
                }
            }

            if (string.IsNullOrEmpty(prefix))
            {
                prefix = "AST"; // 默认前缀
            }

            // 格式: 前缀(3位) + 序号(3位) = 6位，确保不超过10位
            // 例如: ABC001, XYZ999
            string sequence = index.ToString("D3"); // 3位序号

            // 如果前缀+序号超过10位，截断前缀
            string detailNum = prefix + sequence;
            if (detailNum.Length > 10)
            {
                detailNum = detailNum.Substring(0, 10);
            }

            return detailNum;
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}